/**
 * 
 */
package org.compiere.process;

import java.util.Properties;
import java.util.logging.Level;

import org.compiere.model.MColumn;
import org.compiere.model.MTable;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

/**
 * @author A.Kulantayev
 *
 */
public class ReplacerProcess extends SvrProcess {
	/** Current context */
	private Properties m_ctx;
	private ProcessInfo pi;
	private int p_AD_Table_ID;
	private int p_AD_Column_ID;
	@Override
	protected void prepare() {
		log.info("");
		m_ctx = Env.getCtx();
		pi = getProcessInfo();
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals("AD_Table_ID")) 
				p_AD_Table_ID  = para[i].getParameterAsInt();
			else if (name.equals("AD_Column_ID")) 
				p_AD_Column_ID  = para[i].getParameterAsInt();
			else
				log.log(Level.SEVERE, "Unknown Parameter: " + name);
		}	
	}

	@Override
	protected String doIt() throws Exception {
		
		MTable table = new MTable(m_ctx, p_AD_Table_ID, get_TrxName());
		String tableName = table.getTableName(m_ctx, p_AD_Table_ID);
		
		MColumn column = new MColumn(m_ctx, p_AD_Column_ID, get_TrxName());		
		String columnName = column.getColumnName();
		String sql = "UPDATE "+tableName+" SET "+columnName+" = REPLACE("+columnName+",'\"','''')";
		DB.executeUpdate(sql, get_TrxName());
/**
 * 
 *		String sql = "SELECT "+tableName+"_ID, "+columnName+" FROM "+tableName+" WHERE AD_Client_ID = "+Env.getAD_Client_ID(m_ctx)+" AND AD_Org_ID = "+Env.getAD_Org_ID(m_ctx);
 *		PreparedStatement pstmt = null;
 *		ResultSet rs = null;
 *		String colCurrentValue = null;
 *		int curRecord_ID = 0;
 *		String editValue = null;
 *		String tempStr = "\"";
 *		int i = 0;
 *		try{
 *			pstmt = DB.prepareStatement(sql, get_TrxName());
 *			rs = pstmt.executeQuery();
 *			while(rs.next()){
 *				curRecord_ID = rs.getInt(1);
 *				colCurrentValue = rs.getString(2);
 *				if(colCurrentValue.indexOf(tempStr)> 0){
 *					System.out.println("№ "+i+" : \n");
 *					System.out.println("before :"+colCurrentValue);
 *					editValue = colCurrentValue.replace(tempStr, "'");
 *					System.out.println(" after :"+editValue);
 *					
 *					String rrr=  "UPDATE "+tableName+" SET "+columnName+" = "+editValue+" WHERE "+tableName+"_ID = "+curRecord_ID;
 *					//DB.executeUpdate("UPDATE "+tableName+" SET "+columnName+" = "+editValue+" WHERE "+tableName+"_ID = "+curRecord_ID, get_TrxName());
 *					i++;
 *				}
 *			}
 *			
 *		}catch(Exception e){
 *			log.log(Level.SEVERE, sql, e);
 *		}finally{
 *			DB.close(rs, pstmt);
 *			rs = null; pstmt = null;
 *		}
 */		
		return Msg.translate(m_ctx, "Success");
	}

}
